package com.bitbank.smartdevice.util

import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer


/**
 *  Date：2018/11/23
 *  Author：xulee
 *  Desc：
 */
class RxUtils {

    companion object {
        @JvmStatic
        fun <T> execute(iCallback: ICallback<T>) {
            Observable.create(ObservableOnSubscribe<T> { e ->
                try {
                    val result = iCallback.onExecute()
                    if (result != null) {
                        e.onNext(result)
                    }
                } catch (e1: Exception) {
                    e.onError(e1)
                }
            }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<T> {
                    override fun onSubscribe(d: Disposable) {

                    }

                    override fun onNext(value: T) = iCallback.onResult(value)

                    override fun onError(e: Throwable) {
                    }

                    override fun onComplete() {

                    }
                })
        }

    }

    interface ICallback<T> {
        fun onExecute(): T?

        fun onResult(result: T)
    }
}